package com.shuai.user.factory;


import com.shuai.user.constant.LoginTypeEnum;
import com.shuai.user.service.LoginBaseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@Component
@Slf4j
public class LoginStrategyFactory implements InitializingBean {
    /**
     * 策略登录对象存储集合
     */
    private final ConcurrentHashMap<String, LoginBaseService> loginStrategyMap = new ConcurrentHashMap<>();

    @Autowired
    private ApplicationContext context;


    public LoginBaseService getLoginStrategy(LoginTypeEnum loginTypeEnum) {
        return this.loginStrategyMap.get(loginTypeEnum.type);
    }

    @Override
    public void afterPropertiesSet() {
        Map<String, Object> loginStrategyBeanMap = context.getBeansWithAnnotation(com.shuai.user.annotation.LoginStrategyService.class);
        // 将登录策略对象向工厂中进行注册
        Set<Map.Entry<String, Object>> entries = loginStrategyBeanMap.entrySet();
        for (Map.Entry<String, Object> entry : entries) {
            LoginBaseService loginBaseServiceBean = (LoginBaseService) entry.getValue();
            this.loginStrategyMap.put(loginBaseServiceBean.getLoginEnumType().type, loginBaseServiceBean);
            log.info("\n成功注册LoginStrategyFactory工厂对象 -------->[{}]\n", loginBaseServiceBean.getClass().toString());
        }
    }
}
